<!-- 用户管理 -->
<template>
  <div class="app-container">
    <div class="allTabContent">
      <!-- <div>
        客户名称:
        <span> 测试 </span>
      </div>
      <div>
        设备数量:
        <span>3</span>
      </div> -->
    </div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="设备列表" name="first">
        <div class="Filters">
          <el-input v-model="filters.key" style="width: 130px" placeholder="设备名称" />
          <!-- <el-input v-model="filters.devSN" style="width: 120px" placeholder="手机号码" /> -->
          <el-select v-model="filters.deviceTypeId" placeholder="设备类型" style="width: 140px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-button type="primary" icon="search" @click="getManagementPage"
            style="margin-left: 10px; margin-right: 10px">
            查询
          </el-button>
          下级
          <el-switch v-model="switchvalue" @change="switchbtn" />
        </div>
        <div class="Filters2">

          <el-button-group class="ml-4" style="display: flex;">
            <el-button v-for="(item, index) in statulist" type='primary' :plain='item.trues'
              @click="changestatu(index, item)">{{ item.label }}{{ item.value }}</el-button>

          </el-button-group>
          <el-button type="primary" @click="transferdevice(1)">设备状态</el-button>
          <el-button type="primary" @click="transferdevice(2)">转移设备</el-button>
          <el-button type="primary" @click="transferdevice(3)">续期</el-button>
          <el-button type="primary" @click="transferdevice(4)" :disabled="subbtn">批量指令</el-button>
          <el-button type="primary" @click="transferdevice(5)">修改规格</el-button>

          <el-button type="primary" @click="transferdevice(6)">导出设备</el-button>
          <el-button type="primary" @click="copyID(1)">复制ID</el-button>
          <el-button type="primary" @click="copyID(2)">复制BT码</el-button>
          <el-button type="primary" @click="transferdevice(7)">列配置</el-button>
          <el-popover placement="bottom" :width="30" trigger="hover" content="">
            <template #reference>
              <el-button type="success">更多</el-button>
            </template>
            <div class="popover-content">
              <div class="popover-item" @click="mores(1)">电池转出</div>
              <div class="popover-item" @click="mores(2)">导出二维码</div>
              <div class="popover-item" @click="mores(3)">复制</div>
            </div>
          </el-popover>
        </div>
        <el-table v-loading="loading" ref="multipleTable" :data="pageData.data.records"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" />
          <el-table-column v-for="(item, index) in headerslist" :key="index" :label="item.name" :property="item.fileId"
            align="center" :width="getColumnWidth(headerslist.length)" />

          <el-table-column label="操作" fixed="right" width="220">

            <template #header>
              <el-button type="text" size="small" @click="resetsel">重置筛选</el-button>
            </template>
            <template #default="scope">
              <el-button type="text" size="small" @click="handleClicks(scope.row, 1)">BMS</el-button>
              <el-button type="text" size="small" @click="handleClicks(scope.row, 2)">定位</el-button>
              <el-button type="text" size="small" @click="handleClicks(scope.row, 3)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination @pagination="getManagementPage" v-if="filters.pages.total > 0" v-model:total="filters.pages.total"
          v-model:page="filters.pages.current" v-model:limit="filters.pages.size" />
      </el-tab-pane>
      <el-tab-pane label="下级客户" name="second">
        <el-table v-loading="loading" :data="pageData.data.records" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column v-for="(item, index) in pageData.headers" :key="index" :label="item.name"
            :property="item.fileId" align="center" width="180" />
          <el-table-column label="操作" fixed="right" width="220">
          </el-table-column>
        </el-table>

        <pagination v-if="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" />
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="hosvisible" class="" :close-on-click-modal="false" :title="opentitle" width="1300">
      <div v-if="typeValue == 9" class="block" style="display:flex">
        <el-radio-group v-model="exportCode" style="margin:30px;">
          <el-radio value="1">导出设备二维码</el-radio>
          <el-radio value="2">导出设备编号(BT码)二维码</el-radio>
        </el-radio-group>
      </div>
      <div v-if="typeValue == 8" class="block" style="display:flex">
        <div style="display: flex;">
          客户名称：<el-input v-model="exportcustomer" style="width: 240px" placeholder="Please input" />
          <el-popover placement="top-start" title="" :width="200" trigger="hover" content="若是不输入用户将直接转为上级，输入则转给指定用户">
            <template #reference>
              <div
                style="background-color: #444;height: 20px;width: 20px; border-radius: 50%;text-align: center;  line-height: 20px;margin: auto 10px">
                !</div>
            </template>
          </el-popover>
        </div>

        <span style="color: red;">
          慎重提示:电池设备号将会被移出本账号，同时会失去对该电池的控制权
        </span>

      </div>
      <div v-if="typeValue == 2" class="block" style="display:flex">
        <span>客户列表：</span>
        <el-popover :visible="popvisible" trigger="click" placement="bottom" :width="300">
          <el-tree style="max-width:600px;" node-key="id" :data="treeList" :props="defaultProps"
            @node-click="changetree" />
          <template #reference>
            <el-input v-model="inputvalue" style="width: 240px" :placeholder="inputText" />
          </template>
        </el-popover>
      </div>
      <div v-if="typeValue == 3">
        <div>
          <span>续费年限：</span>
          <el-radio-group v-model="Renewalradio">
            <el-radio value="1" size="large">1年30币</el-radio>
            <el-radio value="2" size="large">2年60币</el-radio>
            <el-radio value="2" size="large">终身120币</el-radio>

          </el-radio-group>
        </div>
        <div>
          共计：0（币） 其中保号费用：5（币）<span style="color: red;">续费成功后，设备最快在半小时内上线</span>
        </div>

      </div>
      <div v-if="typeValue == 4">
        <!-- <div> -->
        <!-- <el-cascader :options="batchoptions" clearable @change="changetree" :props="defaultProp" /> -->
        <!-- <deviceSetup :ld="deviceld" /> -->

        <!-- </div> -->
        <!-- <div style="margin-top: 10px;">
        <el-date-picker
        v-model="batchtime"
        type="datetime"
        placeholder="指令发送时间"
        format="YYYY/MM/DD hh:mm:ss"
        value-format="YYYY-MM-DD h:m:s a"
      />
      </div> -->
      </div>
      <div v-if="typeValue == 5">
        <el-select v-model="specificationvalue" placeholder="设备规格" size="large" style="width: 240px">
          <el-option v-for="item in specificationoptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>


      </div>
      <div style="padding:15px" v-if="typeValue !== 4">
        <el-button type="primary" size="small" @click="adddevice">追加设备</el-button>
        <el-button type="primary" size="small" @click="clearseldata">清除</el-button>
        <el-button type="primary" size="small" @click="copyID(1)">复制ID</el-button>
        <el-button type="primary" size="small" @click="copyID(2)" v-if="typeValue == 1">复制BT码</el-button>
        <el-button type="primary" size="small" v-if="typeValue == 1">导出设备</el-button>
        <!-- <el-button type="primary" size="small"  v-if="typeValue==1">重置筛选</el-button> -->
        <el-button type="primary" size="small" v-if="typeValue == 1" @click="newget">刷新</el-button>
        <span style="margin:  0 10px;">总共：0个</span>
        <span style="margin:  0 10px;" v-if="typeValue == 3">（2G网络设备：0个，4G网络设备：1个）</span>

      </div>
      <div v-if="typeValue !== 4">
        <el-table :data="seldata" ref="listref" style="width: 100%" v-loading="loading"
          @selection-change="handleSelectionChangetialog">
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-if="typeValue == 1 || typeValue == 2 || typeValue == 3 || typeValue == 4 || typeValue == 5 || typeValue == 8 || typeValue == 9"
            prop="device_name" label="设备名称" width="">
          </el-table-column>
          <el-table-column
            v-if="typeValue == 1 || typeValue == 2 || typeValue == 3 || typeValue == 4 || typeValue == 5 || typeValue == 8 || typeValue == 9"
            prop="device_code" label="设备号码" width="">
          </el-table-column>
          <el-table-column v-if="typeValue == 3" prop="device_code" label="网络" width="">
          </el-table-column>
          <el-table-column v-if="typeValue == 1" prop="device_code" label="主板型号" width="">
          </el-table-column>
          <el-table-column v-if="typeValue == 1 || typeValue == 3" prop="device_code" label="过期时间" width="">
          </el-table-column>
          <el-table-column v-if="typeValue == 3" prop="device_code" label="保号费(币)" width="">
          </el-table-column>
          <el-table-column label="所属客户"
            v-if="typeValue == 2 || typeValue == 3 || typeValue == 4 || typeValue == 5 || typeValue == 8 || typeValue == 9">
            <template #default="scope">{{ inputText }} </template>
          </el-table-column>
          <el-table-column v-if="typeValue == 5" prop="device_code" label="设备规格" width="">
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">

            <template #default="scope">
              <el-button type="text" size="small" @click="deleteList(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="text-align: center;margin: 20px;">
        <el-checkbox v-if="typeValue == 3" v-model="Renewalchecked" label="续费协议" size="large"
          style="margin-right: 10px;" />
        <el-button v-if="typeValue == 3" type="primary" @click="sumbitbtn">微信支付</el-button>
        <el-button v-if="typeValue == 3" type="primary" @click="sumbitbtn">余额支付</el-button>
        <el-button v-if="typeValue == 2 || typeValue == 4 || typeValue == 8 || typeValue == 9" type="primary"
          @click="sumbitbtn">确定</el-button>
        <el-button @click="closedialog()">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="detailvisible" class="" @close="detailvisible = false" title="详情" width="1000">
      <div>
        <el-descriptions :title="detaildata.device_name">
          <el-descriptions-item label="ID">
            {{ detaildata.id }} </el-descriptions-item>
          <!-- <el-descriptions-item label="设备名称">{{detaildata.device_name}}</el-descriptions-item> -->
          <el-descriptions-item label="设备号码">{{ detaildata.device_code }}</el-descriptions-item>
          <el-descriptions-item label="主板型号">{{ detaildata.device_model }}</el-descriptions-item>
          <el-descriptions-item label="铁塔编号">{{ detaildata.tower_number }}
          </el-descriptions-item>
          <el-descriptions-item label="定位时间">
            {{ detaildata.position_time }} </el-descriptions-item>
          <el-descriptions-item label="到期时间">
            {{ detaildata.expired_time }} </el-descriptions-item>

        </el-descriptions>
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <el-button type="primary" @click="detailvisible = false">确定</el-button>
        <!-- <el-button @click="hosvisible = false">关闭</el-button> -->
      </div>
    </el-dialog>
    <el-dialog v-model="showvisible" class="" @close="showvisible = false" title="列表项显示筛选" width="1000">
      <div style="padding: 15px 25px;">
        全选 <el-switch @change="changgeALL" v-model="allshow" />
      </div>
      <el-form :model="form" label-width="auto">
        <div style="width: 100%;display: flex;flex-wrap: wrap;">
          <div style="width: 30%;" v-for="(item, index) in pageData.headers" v-show="index >= 3">
            <el-form-item :label="item.name">
              <el-switch v-model="item.show" />
            </el-form-item>
          </div>
        </div>
        <div style="width: 100%;text-align: center">
          <el-button type="primary" @click="showsubmit">完成</el-button>

        </div>
      </el-form>
    </el-dialog>
    <el-dialog v-model="Exportvisible" class="" @close="Exportvisible = false" title="导出设备" width="400">
      <div>
        <el-radio-group v-model="Exportradio">
          <el-radio value="1" size="large">导出当前运营商所有设备信息</el-radio>
          <el-radio value="2" size="large">导出列表中的设备信息</el-radio>

        </el-radio-group>
      </div>
    </el-dialog>
    <el-dialog v-model="addshow" class="" @close="addshow = false" title="追加设备" width="500">
      <div>
        <el-radio-group v-model="addradio">
          <el-radio value="1" size="large">设备号码</el-radio>
          <el-radio value="2" size="large">设备编号(BT码)</el-radio>
        </el-radio-group>
      </div>
      <div style="color: red;">
        每行一个完整的设备编号(BT码)号码
      </div>
      <div style="margin: 10px 0;">
        总共:{{ linenum }}个 正确编码{{ properctcodeNum }}个 <span>重复或错误设备{{ errorctcodeNum }}个</span>
      </div>

      <div>
        <el-input @input="changetext" v-model="addtextarea" :style="inputStyle" :rows="5" type="textarea"
          placeholder="Please input" />
        <el-input @input="changetext" v-if="errorctcodeNum >= 1" v-model="errortextarea" style="width: 48%" :rows="5"
          type="textarea" placeholder="Please input" />
      </div>
      <div style="width: 100%;text-align: center;margin-top: 10px">
        <el-button type="primary" :disabled="properctcodeNum <= 0" @click="addsubmit">确定</el-button>
      </div>


    </el-dialog>

    <el-dialog title="复制" v-model="selcodeshow" width="400px" :close-on-click-modal=false>
      <el-radio-group v-model="selectedCode" style="margin: 30px 0;">
        <el-radio value="1">复制当前运营商ID码</el-radio>
        <el-radio value="2">复制当前运营商BT码</el-radio>
      </el-radio-group>



      <div slot="footer" class="dialog-footer" style="width: 100%;text-align: center;">
        <el-button @click="selcodeshow = false">取 消</el-button>
        <el-button type="primary" @click="submitSelection">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量指令" v-model="poinsvisible" width="1000px" :close-on-click-modal=false>
      <el-tabs type="border-card">
        <el-tab-pane v-for="(item, index) in tabList" :key="item.pointGroupId" :label="item.pointGroupName">
          <div style="display: flex; flex-wrap: wrap; height: 600px; width: 100%;padding: 20px 40px;overflow-y:scroll">
            <div v-for="(subItem, subindex) in item.pointInfoList"
              style="flex: 0 0 50%; box-sizing: border-box; padding: 10px;display: flex;">
              <div style="width: 30%;">{{ subItem.pointName }}：</div>

              <el-input v-model="subItem.value" placeholder="Please input"
                v-if="subItem.pointType == 'INT' || subItem.pointType == 'STRING'" style="width: 35%;height: 30px;" />
              <div @change="addtabitem(subItem)" v-if="subItem.pointType == 'ENUM' || subItem.pointType == 'BUTTON'">
                <el-select @change="addtabitem(subItem)" v-model="subItem.value" placeholder="Select" size="large"
                  style="width: 240px;">
                  <el-option v-for="item in subItem.contents" :key="item.value" :label="item.name"
                    :value="item.value" />
                </el-select>

              </div>

            </div>
          </div>
          <div style="width: 100%;text-align: center;margin-bottom: 20px;">
            <el-button type="primary" @click="setsubmit()">Primary</el-button>

          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { TabsPaneContext } from "element-plus";
import DeviceTypeApi, { typeOptions } from "@/api/deviceType"
import DeviceApi, { distributeDevice } from "@/api/device"
import downloadApi from "@/api/download"
import filesApi from "@/api/files";
import CustomerAPI from "@/api/customer";
import { useRoute, useRouter } from 'vue-router';
import DeviceManagementApi, { ManagementPage, ManagementPageList } from "@/api/deviceManagement"
import useClipboard from 'vue-clipboard3'
import pointGroupApi from "@/api/pointGroup";
let route = useRoute()
let router = useRouter()

let opentitle = ref('')
function addtabitem(item: any) {
  console.log(item);
}
// 导出二维码
let exportCode = ref('1')

// 导出电池
let exportcustomer = ref('')
let customerAccount = ref('')

// 批量指令
// const props = defineProps({
//   ld: {
//     type: String,
//     required: true,
//   },
// });
// function changeTab(){
//   gettabvalue(tabList.value[tabValue.value].pointGroupId)

// }
interface tabtype {
  pointGroupId: string,
  pointGroupName: string,
  pointInfoList: [{
    "pointCode": string;
    "pointName": string;
    "pointType": string;
    'value': string;
    contents?: [
      {
        'name': string,
        'value': string
      }
    ];
  }

  ]
}
let tabList = ref<tabtype[]>([])
let tabvalueSle = ref([])
let deviceld = ref<any>('')
interface bactype {
  pointCode: string;
  value: string
}

function setsubmit() {
  let bacthdata = {
    deviceTypeId: seldata.value[0].device_type_id,
    deviceIdList: [''],
    property: <bactype[]>[]
  }

  bacthdata.deviceIdList = []
  for (let i in seldata.value) {
    console.log(seldata.value[i].id, 'seldata.value[i].id');

    bacthdata.deviceIdList.push(seldata.value[i].id)
  }
  for (let i in tabList.value) {
    for (let n in tabList.value[i].pointInfoList) {
      if (tabList.value[i].pointInfoList[n].value !== '') {
        let datas = {
          pointCode: tabList.value[i].pointInfoList[n].pointCode,
          value: tabList.value[i].pointInfoList[n].value
        }
        bacthdata.property.push(datas)
      }
    }
  }
  if (bacthdata.property.length >= 1) {
    downloadApi.batchDownloadProperty(bacthdata).then(() => {
      ElMessage({
        message: '复制成功',
        type: 'success',
      })
      poinsvisible.value = false
    })
  } else {
    ElMessage({
      message: '请先设置参数',
      type: 'warning',
    })
  }
}
// 选择复制编码选项
let selcodeshow = ref(false)
let selectedCode = ref('1')
function submitSelection() {
  console.log(selectedCode.value);

  if (selectedCode.value == '1') {
    copyID(1)
  } else {
    copyID(2)
  }
}
// 状态栏
interface statustype {
  value: number;
  name: string;
  label: string;
  trues: boolean
}
let statulist = ref<statustype[]>(
  [
    {
      value: 0,
      name: '',
      label: '全部',
      trues: false
    },
    // {
    //   label:'正常',
    //   trues:true
    // },
    {
      value: 0,
      name: 'OFFLINE',
      label: '在线',
      trues: true
    },

    {
      value: 0,
      name: 'ONLINE',
      label: '离线',
      trues: true
    },
    {
      value: 0,
      name: 'NOT_ENABLED',
      label: '未启用',
      trues: true
    },
    // {
    //   label:'未过期',
    //   trues:true
    // },
    {
      value: 0,
      name: 'EXPIRED',
      label: '已过期',
      trues: true
    },

    {
      value: 0,
      name: 'SCRAPED',
      label: '已报废',
      trues: true
    }
  ]
)




// 下级按钮
let switchvalue = ref(true)


let allshow = ref(false)
let showvisible = ref(false)
// 通过defineProps接收父组件的值
const fatherElement = defineProps({
  // 接收传值   此处的father就是父组件的自定义名称 
  customerId: {
    type: String,  // 数据类型
    default: "1"  // 未传值时的默认值
  }
})
const form = reactive({
  delivery: false,

})
// 续期数据
let Renewalradio = ref('1')
let Renewalchecked = ref(true)

// 批量指令
const batchvalue = ref('')

let batchoptions = [
  {
    value: 'Option1',
    label: 'Option1',
  },

]
let batchtime = ref('')




// 修改规格数据
const specificationvalue = ref('')

const specificationoptions = [
  {
    value: 'Option1',
    label: 'Option1',
  },
  {
    value: 'Option2',
    label: 'Option2',
  },
  {
    value: 'Option3',
    label: 'Option3',
  },
  {
    value: 'Option4',
    label: 'Option4',
  },
  {
    value: 'Option5',
    label: 'Option5',
  },
]

// 导出设备
let Exportvisible = ref(false)
let Exportradio = ref('1')



// 列表表头
interface Header {
  name: string;
  fileId: string;  // 假设 fileId 的类型是 string
  show: boolean;    // show 是一个布尔值
}
let headerslist = ref<Header[]>([])
let popvisible = ref()
let hosvisible = ref(false)
let detailvisible = ref(false)
let detaildata = ref(
  {
    "device_name": "测试设备",
    "last_online_time": "",
    "device_model": "型号",
    "tower_number": "",
    "device_code": "12345",
    "expired_time": "",
    "id": "1839924051976630273",
    "device_spec": "规格",
    "factory_time": "",
    "position_time": "2024-10-08 17:35:49"
  }
)
// let customerlist=reactive([])
let inputvalue = ref('')
let contactId = ref()
let inputText = ref('')
const defaultProps = {
  children: 'children',
  label: 'customerName',
}
interface Trees {
  customerName?: string
  children?: Trees[]
}
let treeList = reactive<any>([])
// const DeptTrees = ref<any>()
console.log(fatherElement.customerId)  // 打印父组件的值：user
const activeName = ref("first");
const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);


function getColumnWidth(length: any) {
  return length <= 3 ? '' : '200'; // 当列数大于等于5时，宽度为100，其他情况为auto
}

// 转移设备客户列表改变
function changetree(node: any) {
  console.log(node, '---');
  contactId.value = node.id
  inputvalue.value = node.customerName

}

// 更多
// 
function mores(type: any) {
  switch (type) {
    case 1:
      console.log("Type is 1");
      transferdevice(8)
      // 处理类型1的逻辑
      break;
    case 2:
      transferdevice(9)
      // 处理类型2的逻辑
      break;
    case 3:
      console.log(type);

      selcodeshow.value = true

      // 处理类型3的逻辑
      break;
    default:
      console.log("Unknown type");
      // 处理默认情况
      break;
  }


}
// 指定要删除的属性
function removeSpecifiedProperties(obj: any, properties: string[]) {
  properties.forEach((property) => {
    if (obj[property] === '' || obj[property] === undefined) {
      delete obj[property];
    }
  });
}

// 切换状态
function changestatu(index: any, item: any) {
  statulist.value.forEach((item, i) => {
    if (i === index) {
      item.trues = false; // 当前索引的 trues 设置为 false
    } else {
      item.trues = true; // 其他索引的 trues 设置为 true
    }
  });

  switch (item.name) {
    case 'NORMAL':
      filters.deviceStatus = 'NORMAL'
      filters.expireStatus = ''
      filters.onlineStatus = ''

      break;
    case 'ONLINE':
      filters.deviceStatus = ''
      filters.expireStatus = ''
      filters.onlineStatus = 'ONLINE'

      break;
    case 'OFFLINE':
      filters.deviceStatus = ''
      filters.expireStatus = ''
      filters.onlineStatus = 'OFFLINE'

      break;
    case 'NOT_ENABLED':
      filters.deviceStatus = 'NOT_ENABLED'
      filters.expireStatus = ''
      filters.onlineStatus = ''

      break;
    case 'NOT_EXPIRED':
      filters.deviceStatus = ''
      filters.expireStatus = 'NOT_EXPIRED'
      filters.onlineStatus = ''

      break;
    case 'EXPIRED':
      filters.deviceStatus = ''
      filters.expireStatus = 'EXPIRED'
      filters.onlineStatus = ''

      break;
    case 'SCRAPED':
      filters.deviceStatus = 'SCRAPED'
      filters.expireStatus = ''
      filters.onlineStatus = ''


      break;
    default:
      filters.deviceStatus = ''
      filters.expireStatus = ''
      filters.onlineStatus = ''



  }
  removeSpecifiedProperties(filters, ['expireStatus', 'onlineStatus', 'deviceStatus']);

  getManagementPage()


}

// 全选
function changgeALL(val: any) {
  console.log(val, '')
  if (val) {
    for (let i in pageData.headers) {
      pageData.headers[i].show = true
    }
  } else {
    for (let i in pageData.headers) {
      if (Number(i) >= 3) {
        pageData.headers[i].show = false
        console.log('shishenme ')

      } else {
        console.log('meijinlme')
        pageData.headers[i].show = true
      }
      console.log(pageData.headers[i], Number(i))


    }
  }
}

interface customertype {
  device_name: string;
  last_online_time: string;
  device_model: string;
  tower_number: string;
  device_code: string;
  expired_time: string;
  id: string;
  device_spec: string;
  factory_time: string;
  position_time: string;
  device_type_id: string;
}

let seldata = ref<customertype[]>([])
let oldseldata = ref<customertype[]>([])
// 关闭弹窗
function closedialog() {
  hosvisible.value = false
  seldata.value = oldseldata.value
}
// 确定转移设备
function sumbitbtn() {
  console.log(typeValue.value, '-----------------------');
  if (seldata.value.length <= 0) {
    ElMessage({
      message: '请先添加要进行操作的设备',
      type: 'warning',
    })

  } else {

    switch (typeValue.value) {
      case 1:
        break;
      case 2:
        let data = {
          customerId: `${contactId.value}`,
          deviceId: [] as string[]
        }
        if (seldata.value.length >= 1) {
          for (let i in seldata.value) {
            console.log(seldata.value[i].id)
            data.deviceId.push(seldata.value[i].id)
          }
          console.log(typeof (data.customerId), data)

          DeviceApi.BatchAllocate(data).then((res) => {
            ElMessage({
              message: '配对成功',
              type: 'success',
            })
            hosvisible.value = false
          })
        } else {
          ElMessage({
            message: '请先选择设备',
            type: 'warning',
          })
        }
        treeList = []
        break;
      case 9:
        let dataTo = {
          inputStrings: ['']
        }
        dataTo.inputStrings = []
        if (exportCode.value == '1') {
          for (let i in seldata.value) {
            dataTo.inputStrings.push(seldata.value[i].id)
          }
        } else {
          for (let i in seldata.value) {
            dataTo.inputStrings.push(seldata.value[i].tower_number)



          }
        }
        filesApi.generateQrCodes(dataTo).then(() => {
        })
        break;
      case 8:

        let outdata = {
          customerName: exportcustomer.value,
          deviceIdList: ['']
        }
        outdata.deviceIdList = []
        for (let i in seldata.value) {
          outdata.deviceIdList.push(seldata.value[i].id)
        }
        console.log(outdata);

        DeviceManagementApi.batchTurnOut(outdata).then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
        })
        break;
      default:
        break;
    }
  }


}

// 删除所选项
function deleteList(row: any) {
  console.log(row.id)
  // console.log(customerlist,'--111-----')

  seldata.value = seldata.value.filter(i => i.id !== row.id);
  console.log(seldata.value, '-------')


}
let pageData = reactive<ManagementPageList>({
  headers: [],
  data: {
    current: 0,
    pages: 0,
    size: 0,
    total: 0,
    records: []
  }
});
// let seldata.value=ref([])
let options = reactive<typeOptions[]>([{
  "label": 'test',
  "value": "1"
}]);

let filters = reactive<ManagementPage>({
  "pages": {
    "current": 1,
    "size": 10,
    "total": 0,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  key: undefined,
  // deviceStatus:'',
  // onlineStatus:'',
  // expireStatus:'',
  deviceTypeId: '',
  customerId: '',
  isChild: true
});

// 列配置

function showsubmit() {
  headerslist.value = [];
  headerslist.value = pageData.headers.filter((header: any) => header.show);
  ElMessage({
    message: '配置成功',
    type: 'success',
  })
  showvisible.value = false
}
const { toClipboard } = useClipboard();
// 追加设备
let addtextarea = ref('')
let errortextarea = ref('')
let addradio = ref('1')//1是id 2是编码
let addshow = ref(false)
let linenum = ref(0)
let errorctcodeNum = ref(0)
let properctcodeNum = ref(0)
let errcodetextlist = reactive<string[]>([])
let propercttextlist = reactive<string[]>([])



// 输入编码
function changetext(text: any) {
  if (addradio.value == '1') {
    linenum = calculateLineCount(text);

    const lines = text.split('\n');
    console.log(lines, '000');

    properctcodeNum.value = 0; // Initialize error count
    errcodetextlist = []; // Make sure to reset the error list each time
    propercttextlist = []
    for (const line of lines) {
      const trimmedLine = line.trim();

      if (trimmedLine.length > 0 && trimmedLine.length === 12) {
        propercttextlist.push(trimmedLine);

        properctcodeNum.value++; // Increment error count for valid lines
      } else {
        errcodetextlist.push(trimmedLine);
      }
    }
    errorctcodeNum.value = lines.length - properctcodeNum.value
    if (errorctcodeNum.value >= 1) {

    }
    errortextarea.value = errcodetextlist.join('\n');
    console.log(propercttextlist, '对的', errcodetextlist, '错的');

  }




}
// 输入框样式
const inputStyle = computed(() => {
  if (errorctcodeNum.value >= 1) {
    return {
      width: '48%',
      marginRight: '4%',
    };
  } else {
    return {
      width: '100%',
      marginRight: '0',

    };
  }
});
let addlist = reactive([])
let countInSel = ref()

// 追加设备确定按钮
function addsubmit() {

  // 计算在 seldata 中存在的设备数量
  const countInSeldata = propercttextlist.reduce((count, item) => {
    return count + (seldata.value.some(m => m.device_code === item) ? 1 : 0);
  }, 0);

  // 过滤掉 seldata.value 中存在的设备代码
  propercttextlist = propercttextlist.filter(item => {
    return !seldata.value.some(m => m.device_code === item);
  });
  console.log(countInSeldata, linenum);

  // 输出结果
  // console.log(11111111111111,'countInSeldata',countInSeldata,linenum);
  // let nums=linenum
  if (countInSeldata == 0) {
    //  else{
    console.log('===============');

    propercttextlist.forEach(item => {
      // 检查设备代码是否在 seldata 中
      const foundRecord = pageData.data.records.find((m: { device_code: string; }) => {
        return m.device_code === String(item);
      });


      if (foundRecord) {
        seldata.value.push(foundRecord);
        // if(countInSeldata==0){
        //   ElMessage({
        //   message: '新增成功',
        //   type: 'success',
        //   })
        // }

        //   if(errorctcodeNum.value>=0){
        //   console.log(11111110);
        //   let numbers=linenum-countInSeldata
        addshow.value = false
        //   ElMessage({
        //     message:"包含重复或不在此账号下的设备，数量为:"+errnumbers,
        //     type: 'warning',
        //   })
        // }
      } else {
        ElMessage({
          message: "包含重复或不在此账号下的设备",
          type: 'warning',
        })
        addshow.value = false

      }
    });
    // }

  } else {
    console.log(999999999999999999);

    addshow.value = false
    ElMessage({
      message: "包含重复或不在此账号下的设备，数量为:" + countInSeldata,
      type: 'warning',
    })
  }
  // }
}
function calculateLineCount(text: any) {
  return text.split('\n').filter((line: string) => line.trim() !== '').length;
}
function adddevice() {
  addtextarea.value = ''
  errortextarea.value = ''
  addshow.value = true

}
// 刷新
function newget() {
  loading.value = true;
  seldata.value = seldata.value
  setTimeout(() => {
    loading.value = false;
  }, 500);

}
// 复制BT码 id
function copyID(type: any) {
  if (seldata.value.length >= 1) {
    console.log('seldata.value', seldata.value, type)
    let text = ''
    if (type == 1) {
      for (let i in seldata.value) {
        text += seldata.value[i].id + "\n"; // 每个 id 后面加上换行符
      }
    } else {
      for (let i in seldata.value) {
        text += seldata.value[i].tower_number + "\n"; // 每个 id 后面加上换行符
      }
    }
    toClipboard(text)
    ElMessage({
      message: '复制成功',
      type: 'success',
    })
    selcodeshow.value = false
  }
  else {
    ElMessage({
      message: '请先选择要复制内容的设备',
      type: 'warning',
    })
  }
}

// 清除弹窗列表
function clearseldata() {
  console.log('1111');

  seldata.value = []
}

//1 设备状态  2 转移设备 3 续期 4 批量指令  8 电池转出  9 导出二维码
let typeValue = ref()
let poinsvisible = ref(false)

function transferdevice(type: any) {
  console.log(type, '000');

  typeValue.value = type
  if (seldata.value.length >= 1) {

    switch (type) {
      case 1:
        if (seldata.value.length >= 1) {
          hosvisible.value = true
          opentitle.value = '设备状态'
        } else {
          ElMessage({
            message: '请先选择要设置的设备设备',
            type: 'warning'
          })



        }
        break;
      case 2:
        // if(seldata.value.length>=1){

        CustomerAPI.getCustomerTree().then((ren) => {
          console.log('data', ren, treeList)
          inputText.value = ren.customerName
          contactId.value = ren.id
          treeList.push(ren)
          hosvisible.value = true
          opentitle.value = '设备转移'

          // customerlist=seldata.value
          // console.log(customerlist,contactId.value)
        })
        // }else{
        //   ElMessage({
        //     message: '请先选择要转移的设备',
        //     type: 'warning',
        //   })
        // }
        break;
      case 3:
        hosvisible.value = true
        opentitle.value = '续期'

        break;
      case 4:

        // let data={
        //   deviceTypeId:2
        // }
        let deviceTypeId = seldata.value[0].device_type_id
        tabList.value = []
        pointGroupApi.getPropertyGroupInfo(deviceTypeId).then((res) => {
          // 将 res 赋值给 tabList.value
          tabList.value = res;
          // 遍历 tabList.value 中的每个对象
          tabList.value.forEach((item) => {
            // 检查 pointInfoList 是否存在
            if (item.pointInfoList) {
              // 遍历 pointInfoList 中的每个对象
              item.pointInfoList.forEach((pointInfo) => {
                // 为每个 pointInfo 添加 value 属性
                pointInfo.value = ''; // 设置 value 为 ''
              });
            }
            console.log(tabList.value, '000000');

          });
        });
        poinsvisible.value = true

        break;
      case 5:
        hosvisible.value = true
        opentitle.value = '修改规格'

        break;
      case 6:
        Exportvisible.value = true
        break;
      case 7:
        showvisible.value = true
        break;
      case 8:
        hosvisible.value = true
        opentitle.value = '电池转出'

        break;
      case 9:
        hosvisible.value = true
        opentitle.value = '导出二维码'

        break;
      default:
        console.log('wu')
    }
  } else {
    ElMessage({
      message: '请先选择要设置的设备设备',
      type: 'warning'
    })
  }

}

// 重置筛选
const multipleTable = ref();
function resetsel() {
  multipleTable.value.clearSelection();
}
/** 用户查询参数  */
const queryParams = {
  pageNum: 1,
  pageSize: 10,
};
function handleClicks(data: any, type: number) {
  console.log(data)
  switch (type) {
    case 1:
      router.push({ path: '/bmscontrol/bms', query: { deviceSN: data.device_code } });
      break;
    case 2:
      router.push({ path: '/location/bms', query: { deviceID: data.id } });
      break;
    case 3:

      detaildata.value = data
      detailvisible.value = true
      break;
    default: /* 可选的 */

      return 0;
  }

}
// 弹窗复选框
function handleSelectionChangetialog(selvalue: any) {

}

/** 行复选框选中记录选中ID集合 */
let subbtn = ref(true); // 初始状态

function handleSelectionChange(selection: any) {
  seldata.value = []
  oldseldata.value = []
  seldata.value = selection
  oldseldata.value = selection

  console.log(selection, '000')
  removeIds.value = selection.map((item: any) => item.id);
  let firstDeviceTypeId = null;
  if (seldata.value.length == 1) {
    subbtn.value = false;
  } else {

    for (let i in seldata.value) {
      if (firstDeviceTypeId === null) {
        // 第一次迭代，设置第一个 device_type_id
        firstDeviceTypeId = seldata.value[i].device_type_id;

      } else {
        // 检查当前 device_type_id 是否与第一个一致
        if (seldata.value[i].device_type_id !== firstDeviceTypeId) {
          subbtn.value = true; // 只要有一个不一致，subbtn保持为true
          break; // 退出循环
        }
        subbtn.value = false; // 仍然一致，更新 subbtn 为 false
      }
    }
  }

}
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/** 查询设备类型下拉列表 */
function deviceTypeOptions() {
  DeviceTypeApi.deviceTypeOptions()
    .then((data) => {
      options = data;
      options.unshift(
        {
          "label": '全选',
          "value": ""
        }
      )
      // filters.deviceTypeId = data[0].value;
    })
    .finally(() => {
    });
}
/**
@date: 2024-09-11 11:39:52
查询设备分页列表
*/
// 下级列表
function switchbtn(type: any) {
  filters.isChild = type
  console.log(type);
  getManagementPage()

}

const getManagementPage = useThrottleFn(() => {
  loading.value = true;
  filters.customerId = fatherElement.customerId;
  filters.isChild = switchvalue.value;

  DeviceManagementApi.getManagementPage(filters)
    .then((data) => {
      pageData.headers = data.headers;
      for (let i in pageData.headers) {
        pageData.headers[i].show = true
      }
      headerslist.value = pageData.headers
      pageData.data = data.data;
      filters.pages.total = data.data.total;
      filters.pages.current = data.data.current;
      for (let i in statulist.value) {
        switch (statulist.value[i].name) {
          case '':
            statulist.value[i].value = data.countInfo.total
            break;
          case 'NOT_ENABLED':
            statulist.value[i].value = data.countInfo.notEnable

            break;
          case 'OFFLINE':
            statulist.value[i].value = data.countInfo.offline

            break;
          case 'ONLINE':
            statulist.value[i].value = data.countInfo.online

            break;
          case 'SCRAPED':
            statulist.value[i].value = data.countInfo.scrap

            break;
          case 'EXPIRED':
            statulist.value[i].value = data.countInfo.expired

            break;
          default:
            statulist.value[i].value = 0


        }
      }
    })
    .finally(() => {
      loading.value = false;
    });
}, 1000);
onMounted(() => {
  deviceTypeOptions();
  getManagementPage()
});

defineExpose({
  getManagementPage
})
</script>
<style lang="scss" scoped>
.app-container {
  position: relative;

  .allTabContent {
    display: flex;
    align-items: center;
    position: absolute;
    top: 15px;
    right: 0;

    div {
      margin-left: 26px;
      font-weight: 700;

      span {
        margin-left: 8px;
      }
    }
  }
}

.demo-tabs {
  :deep(.el-tabs__nav-wrap:after) {
    background-color: transparent !important;

  }

  .Filters,
  .Filters2 {
    margin-bottom: 10px;
    display: flex;
    align-items: center;

    &>div {
      margin-right: 5px;
    }
  }
}

.popover-content {
  display: flex;
  flex-direction: column;
  /* 垂直排列 */
}

.popover-item {
  padding: 8px;
  /* 内边距 */
  cursor: pointer;
  /* 鼠标悬停时显示为可点击 */
  transition: background-color 0.3s, color 0.3s;
  /* 动画效果 */
}

.popover-item:hover {
  // background-color: #f0f0f0; /* 悬停时背景色 */
  color: #409EFF;
  /* 悬停时字体颜色 */
}
</style>
